package ophiux.wechatpay.sdk.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ophiux.wechatpay.sdk.common.utils.HttpUtil;
import ophiux.wechatpay.sdk.common.utils.StringUtil;

import com.alibaba.fastjson.JSONObject;

/**
 * 
 * 说明：微信授权<br>
 * <h1>创 建 人: 何海龙   <br></h1>
 * 创建日期: 2017年7月17日上午09:32:28<br>
 * 需要的jar包:fastjson-1.1.41.jar，servlet-api.jar
 */
public class RedirectServlet extends HttpServlet {
	private static final long serialVersionUID = -4943068461691117623L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String code = request.getParameter("code");
		String appid = request.getParameter("appid");
		String appsecret = request.getParameter("appsecret");
		String client_back_url =request.getParameter("client_back_url");//授权后跳转的地址
		response.getWriter().write("code"+code);
		if (StringUtil.isEmpty(code)) {
			response.getWriter().write("用户拒绝授权");
		} else {
			String openId = "";
			if ((StringUtil.isEmpty(appid)) || (StringUtil.isEmpty(appsecret))) {
				openId = "";
			}
			String OAUTH_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APP_ID&secret=APP_SECRET&code=CODE&grant_type=authorization_code";
			String url = OAUTH_URL.replace("APP_ID", appid).replace("APP_SECRET", appsecret).replace("CODE", code);
			String oauResp="";
			try {
				oauResp = HttpUtil.post(url, "");
			} catch (Exception e) {
				e.printStackTrace();
			}
			JSONObject jsonObj = (JSONObject) JSONObject.toJSON(oauResp);
			if (jsonObj.containsKey("errcode")) {
				openId = "";
			} else {
				openId = jsonObj.getString("openid");
			}
 
			StringBuffer sb = new StringBuffer();
			sb.append(client_back_url).append("?").append("&openId=").append(openId);
			response.sendRedirect(sb.toString());
		}
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}